#!/usr/bin/env python3
import os
import sys
import time
import hmac
import json
import hashlib
import requests

def usage():
    print('Viki Downloader - v0.1.0')
    print('usage: viki-dl [episode-link]')

def generate_url(path):
    api_url = 'http://api.viki.io%s&sig=%s'
    api_query = '/v4/%s?app=%s&t=%s&site=www.viki.com&token=None'
    app = '100005a'
    app_secret = 'MM_d*yP@`&1@]@!AVrXf_o-HVEnoTnm$O-ti4[G~$JDI/Dc-&piU&z&5.;:}95=Iad'

    timestamp = int(time.time())
    query = api_query % (path, app, timestamp)
    sig = hmac.new(
        app_secret.encode('ascii'),
        query.encode('ascii'),
        hashlib.sha1
    ).hexdigest()
    return api_url % (query, sig)

def get_video_id(url):
    url = url.split('/')[4]
    video_id = url.split('-')[0]
    return video_id

def run(url):
    video_id = get_video_id(url)

    stream_path = 'videos/%s/streams.json' % video_id
    stream_url = generate_url(stream_path)

    subtitle_path = 'videos/%s/subtitles/%s.%s' % (video_id, 'en', 'vtt')
    subtitle_url = generate_url(subtitle_path)

    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
        'Upgrade-Insecure-Requests': '1',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
    }

    r = requests.get(stream_url, headers=headers)
    data = r.json()
    video_url = data['480p']['http']['url']

    subtitle = requests.get(subtitle_url, headers=headers)
    subtitle_file = video_id + '.vtt'

    with open(subtitle_file, 'w') as f:
        f.write(subtitle.text)

    os.system('mpv --sub-file={} "{}"'.format(subtitle_file, video_url))

if __name__ == '__main__':
    try:
        run(sys.argv[1])
    except:
        usage()
